package com.mysteel.order.web;

import com.mysteel.common.exception.BizCodeEnum;
import com.mysteel.order.exception.CommonException;
import com.mysteel.order.service.OrderService;
import com.mysteel.order.vo.OrderConfirmVo;
import com.mysteel.order.vo.OrderSubmitVo;
import com.mysteel.order.vo.SubmitOrderResponseVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

/**
 * ProjectName: mail
 * ClassName: OrderWebController
 * Description:
 * date: 2021/03/20/020 14:18
 *
 * @author xiaochao
 */
@Slf4j
@Controller
public class OrderWebController {

    @Autowired
    private OrderService orderService;

    @GetMapping("/toTrade")
    public String toTrade(Model model){
        OrderConfirmVo confirmVo = orderService.confirmOrder();
        model.addAttribute("orderConfirmData",confirmVo);
        return "confirm";
    }

    @PostMapping("/submitOrder")
    public String submitOrderInfo(@Validated OrderSubmitVo orderSubmitVo, BindingResult result, Model model, RedirectAttributes redirectAttributes){
        try {
            if (result.hasErrors()){
                throw new CommonException(BizCodeEnum.ORDER_PARAM_INPUT_EXCEPTION.getCode(),BizCodeEnum.ORDER_PARAM_INPUT_EXCEPTION.getMsg());
            }
            SubmitOrderResponseVo responseVo = orderService.submitOrder(orderSubmitVo);
            // 失败跳回结算页
            if (responseVo.getCode() != 1){
                return "redirect:http://order.xcmail.com/toTrade";
            }
            model.addAttribute("submitOrderResponse",responseVo);
        }catch (Exception e){
            log.info("提交订单异常：{}",e);
            return "redirect:http://order.xcmail.com/toTrade";
        }

        return "pay";
    }
}
